// pages/edit-song-menu/index.js
const db = wx.cloud.database()
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

  data: {
    collectionId:"",
    collectionList:[],
    newCollectionUrl:"",
    showCollectionName:false,
    newCollectionName:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id
    this.setData({collectionId:id})
    this.getCollectionInfo()
  },

  //====================获取歌单信息==================
  getCollectionInfo:function(){
    db.collection('collectionMenu').doc(this.data.collectionId).get()
    .then(res=>{
      this.setData({collectionList:res.data})
    })
  },

  //======================更换头像========================
  uploadImageClick(){
    const that = this
    wx.chooseMedia({
      count:1,
      mediaType:['image'],
      sourceType:['album','camera'],
      sizeType:['compressed'],
      camera:'back',
      success(res){
        var filePath = res.tempFiles[0].tempFilePath;
        that.cloudUpload(filePath)
      }
    })

  },
  cloudUpload(filePath){
    var that = this
    wx.cloud.uploadFile({
        cloudPath:Date.now()+".jpg",
        filePath:filePath
    }).then(res=>{
      console.log(res);
      that.setData({
        newCollectionUrl:res.fileID
      })
      that.updateCollectionImage()
    })
  },

  updateCollectionImage(){
    db.collection('collectionMenu').doc(this.data.collectionId).update({
      data:{
        coverImgUrl:this.data.newCollectionUrl
      },
    })
    .then(res=>{
      this.getCollectionInfo()
      Toast('头像修改成功')
    })
    
  },

  //=======================更新歌单名======================
  handleEditCollectionNameClick:function(){
    this.setData({showCollectionName:true})
  },

  onCloseCollectionName:function(){
    this.setData({showCollectionName:false})
  },
  cancelCollectionNameClick:function(){
    this.setData({showCollectionName:false})
  },
  onChangeCollectionName(event){
    var newCollectionName = event.detail
    this.setData({
      newCollectionName
    })
  },
  confirmCollectionNameClick:function(){
    if(!this.data.newCollectionName){
      Toast('歌单名不能为空')
    }
    else if(this.data.newCollectionName !== ""){
      
      db.collection('collectionMenu').doc(this.data.collectionId).update({
        data:{
          name:this.data.newCollectionName
        },
      })
      .then(res =>{
        this.getCollectionInfo()
        this.setData({showCollectionName:false})
        this.setData({newCollectionName:""})
        Toast('更新成功')
      })
    }

  }
})